function memoizeScale(max: number, data: Float32Array) {
  const m: number[] = [];
  return function (v: number) {
    const s = data[v];
    // console.log(`s: ${s}`);
    if (!m[s]) {
      m[s] = (max - data[v]) / max;
    }
    return m[s];
  };
}
export default function drawWaveform(
  canvas: HTMLCanvasElement,
  dataSamples: Float32Array,
  config: WaveformConfig
) {
  const c = canvas.getContext('2d');
  let w = 0,
    x = 0;
  const d = canvas.width,
    g = config.linePercent * canvas.height,
    gw = config.barWidth,
    v = canvas.height - g,
    r = dataSamples.length;
  const scaledSamples = memoizeScale(config.maxVal, dataSamples);

  const increment = config.barWidth + config.gapWidth;

  c!.clearRect(0, 0, canvas.width, canvas.height);
  c!.save();
  c!.beginPath();
  for (let k = 0; k < d; k += increment) {
    const C = scaledSamples(((k / d) * r) | 0);
    const T = (C * g) | 0;
    const S = ((1 - C) * v + g) | 0;
    //Draw Bar
    c!.rect(
      k, // X
      T, // Y
      gw, // W
      S - T + 1
    ); // H

    //Draw Gap
    const A = Math.max(T, w);
    c!.fillStyle = 'transparent';
    c!.fillRect(
      k - config.gapWidth, //X
      A, //Y
      config.gapWidth, //W
      Math.min(S, x) - A
    ); //H

    w = T;
    x = S;
  }

  c!.fillStyle = config.color;
  c!.fill();
  c!.clearRect(0, g, d, 1);
  c!.restore();
}
export interface WaveformConfig {
  maxVal: number;
  linePercent: number;
  barWidth: number;
  gapWidth: number;
  color: string;
}
